package com.example.aliceapp;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import com.example.aliceapp.StorageStack.StorageVO;

import android.bluetooth.BluetoothSocket;

public class BluetoothConnector {

	private static BluetoothConnector instance;
	private BluetoothSocket bSocket;
	private OutputStream oStream;
	private PrintWriter writer;

	private StorageStack stack;

	private BluetoothConnector() {
		stack = new StorageStack();
	}

	public static BluetoothConnector getInstance() {
		if (instance == null) {
			instance = new BluetoothConnector();
		}
		return instance;
	}

	public void setSocket(BluetoothSocket bs) {
		bSocket = bs;
		try {
			oStream = bSocket.getOutputStream();
			writer = new PrintWriter(oStream);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public synchronized void moveForward() {
		writer.println('7');
		writer.flush();
		stack.putCommand('7');
	}

	public synchronized void moveBackward() {
		writer.println('8');
		writer.flush();
		stack.putCommand('8');
	}

	public synchronized void moveRight() {
		writer.println('9');
		writer.flush();
		stack.putCommand('9');
	}

	public synchronized void moveLeft() {
		writer.println(':');
		writer.flush();
		stack.putCommand(':');
	}

	public synchronized void stop() {
		writer.println('S');
		writer.flush();
		stack.putCommand('S');
	}

	public synchronized void moveSouthEast() {
		writer.println('=');
		writer.flush();
		stack.putCommand('=');
	}

	public synchronized void moveSouthWest() {
		writer.println('>');
		writer.flush();
		stack.putCommand('>');
	}
	
	public synchronized void NOS(){
		writer.println('B');
		writer.flush();
		stack.putCommand('B');
	}
	
	public void clearStack(){
		stack.clear();
	}
	
	public void stopSocket(){
		try {
			bSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public synchronized void goHome() {
		long startTime = stack.peek().getTime();
		long ownStartTime = System.nanoTime();
		long currentTime = System.nanoTime();
		long timeElapsed = 0;
		while (!stack.isEmpty()) {
			StorageVO vo = stack.getNextCommand();
			runCommand(vo.getCommand());
			while (currentTime > vo.getTime()) {
				timeElapsed = System.nanoTime() - ownStartTime;
				currentTime = startTime - timeElapsed;
			}
		}

	}

	public synchronized void moveNorthEast() {
		writer.println(';');
		writer.flush();
		stack.putCommand(';');
	}

	public synchronized void moveNorthWest() {
		writer.println('<');
		writer.flush();
		stack.putCommand('<');
	}

	public synchronized void sendAccelerometerValues(char direction,
			char rotationMagnitude) {
		writer.println(direction);
		writer.flush();
		writer.println(rotationMagnitude);
		writer.flush();
	}

	public void runCommand(char command) {
		writer.println(command);
		writer.flush();

	}

}
